<?php
/**
 * Gére les autorisations // Utilise la session
 *
 * @copyright Copyright (c) 2013
 * @version   1.0
 * 
 * @todo commenter la classe
 **/
class Membership
{	
    private $_elevetedPrivilegeMode;
    private $_userId;
    private $_userName;
    private $_userLogin;
 	
	/**
    * Constructor
	* récupere la variable de session
    * 
    * @return void
    */    
    public function __construct () {
		$this->_elevetedPrivilegeMode = false;
		if (isset($_SESSION['UserId']) && isset($_SESSION['User'])) {
			$this->_userId = $_SESSION['UserId'];
			$u = unserialize($_SESSION['User']);
			$this->_userName=$u->_userName;
			$this->_userLogin=$u->_userLogin;
		} else {
			$this->_userId = PHP_INT_MAX;
			$this->_userName = 'anonyme';
		}
    }
	

	public function isAuthenticated ( ) {
		return $this->_userId > 0 && $this->_userId != PHP_INT_MAX;
	}

	
	public function Authentify ($login, $password ) {
		DbConnection::getInstance()->Execute(
			'SELECT U.id, M.name FROM sys_user U inner join sys_member M on U.id = M.id
			 where login = <s:login/> and password = <s:pwd/> ', 
					array( 
						's:login' => $login,
						's:pwd' => $password
						));
	
		
		if ( $row = DbConnection::getInstance()->nextRow())
		{		
			$this->_userId = $row[0];
			$this->_userName =  $row[1];
			$this->_userLogin = $login;
			$_SESSION['UserId'] = $this->_userId;
			$_SESSION['User'] = serialize($this);
			return true;
		}
		return false;
	}
	
	public function getUserId () {
		return $this->_elevetedPrivilegeMode ? 0 : $this->_userId;
	}

	public function getUserName () {
		return $this->_userName;
	}

	public function getUserLogin () {
		return $this->_userLogin;
	}

	public function getPermission ($objectId) {
		return Permission::NONE;
	}
	
	public function StartExecutingWithElevetedPrivilege () {
		$this->_elevetedPrivilegeMode = true;
	}
	

	public function StopExecutingWithElevetedPrivilege () {
		$this->_elevetedPrivilegeMode = false;
	}

} // END class